package serveur;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import java.util.List;

import remote.ClientInterface;
import remote.PrivateInterface;
import remote.PublicInterface;
import remote.Tweet;
import serveur.exception.AlreadyConnectedException;
import serveur.exception.AlreadyExistException;
import serveur.exception.NotExistException;
import serveur.exception.WrongPasswordException;

/**
 * Class representing the public access
 */
public class PublicServer extends UnicastRemoteObject implements PublicInterface {
	protected ServerDatas datas;
	
	protected PublicServer() throws RemoteException {
		super();
		datas = ServerDatas.getInstance();
	}

	@Override
	public boolean inscription(String pseudo, String pswd)
			throws RemoteException {
			try {
				datas.addUser(pseudo, pswd);
				return true;
			} catch (AlreadyExistException e) {
				System.out.println("!! User "+pseudo+" already exist !!");
				
			}
			return false;
	}

	@Override
	public PrivateInterface connection(String pseudo, String pswd, ClientInterface ci)
			throws RemoteException {
		try {
			User u = datas.getUser(pseudo);
			// If wrong password
			if(!u.getPswd().equals(pswd)) throw new WrongPasswordException();
			// If the client is already connected
			if(datas.connected.containsKey(pseudo)) throw new AlreadyConnectedException();
			
			return new PrivateServer(u, ci);
		} catch (NotExistException e) {
			System.out.println("User "+pseudo+" not exist in database");
			return null;
		} catch (WrongPasswordException e) {
			System.out.println("User "+pseudo+" wrong password");
			return null;
		} catch (AlreadyConnectedException e) {
			System.out.println("User "+pseudo+" is already connected");
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	List<String> getUsers() {
		return datas.getUsers();
	}

	@Override
	public List<Tweet> getRecent(int x) throws RemoteException {
		return datas.getRecentTweets(x);
	}

	@Override
	public List<Tweet> getRecent(String htag, int x) throws RemoteException {
		return datas.getRecentTweets(htag, x);
	}
}
